package com.suxii.adapter;

import static com.suxii.netty_demo.activity.ChatActivity.chat_list;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.suxii.netty_demo.R;
import com.suxii.pojo.MyMsg;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import java.lang.reflect.Type;
import com.google.gson.reflect.TypeToken;

public class ChatListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private List<MyMsg> data;
    private Context context;

    final private static int RECEIVE=0;
    final private static int SEND=1;

    public ChatListAdapter() {
    }

    public ChatListAdapter(List<MyMsg> data, Context context) {
        this.data = data;
        this.context = context;
    }

    /*
    定义动态添加数据
     */
    public void addData(MyMsg msg){
        data.add(msg);
        //notifyDataSetChanged();
        notifyItemInserted(getItemCount()-1);

    }
    public void deleteData(){
        data=new ArrayList<>();
        notifyDataSetChanged();

    }

    public String getNewMessage(){
        if (getItemCount()==0){
            return "";
        }
        return data.get(getItemCount() - 1).getMessage();
    }
    /*
    保存聊天信息到本地
     */
    public void savaMessage(Integer uuid){
        String s = new Gson().toJson(data);
        //Log.e("aa",s);
        File file = new File(context.getFilesDir(), uuid + "_message.sx");
        try(var fos = new FileOutputStream(file);
            var bw=new BufferedWriter(new OutputStreamWriter(fos))
        ) {
            bw.write(s);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void savaMessage2(Integer uuid){
        StringBuffer s=new StringBuffer();



        // 3.将序列化的数据保存到指定文件
        File file = new File(context.getFilesDir(), uuid + "_message.sx");
        try(
            var bw=new BufferedWriter(new FileWriter(file))
        ) {
            // 1.获取列表中每条消息，重新组合，整合成String
            for (MyMsg msg : data) {
                // 2.将数据逐条序列化
                s.append(new Gson().toJson(msg)).append("\n");
            }
            bw.write(String.valueOf(s));
            //bw.newLine();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /*
    读取本地缓存消息
     */
    public void findMessage(Integer uuid){
        File file = new File(context.getFilesDir(), uuid + "_message.sx");
        if (file.isFile()) {

            try (var fis = new FileInputStream(file);
                 var br = new BufferedReader(new InputStreamReader(fis))
            ) {
                // s为中间变量，读取全部数据赋值给json
                String s;
                StringBuffer json = new StringBuffer();
                while ((s = br.readLine()) != null) {
                    json.append(s);
                }

                Type listType = new TypeToken<ArrayList<MyMsg>>() {
                }.getType();
                // Gson反序列化，为List
                List<MyMsg> list = new Gson().fromJson(json.toString(), listType);
                //Log.e("aa",json.toString());
                this.data = list;


            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void findMessage2(Integer uuid){
        File file = new File(context.getFilesDir(), uuid + "_message.sx");
        if (file.isFile()) {

            try (var fis = new FileInputStream(file);
                 var br = new BufferedReader(new InputStreamReader(fis))
            ) {
                // s为中间变量，读取全部数据赋值给json
                String s;
                StringBuffer json = new StringBuffer();
                List<MyMsg> list = new ArrayList<>();
                while ((s = br.readLine()) != null) {
                    //json.append(s);
                    list.add(new Gson().fromJson(s,MyMsg.class));
                }

                Type listType = new TypeToken<ArrayList<MyMsg>>() {
                }.getType();
                // Gson反序列化，为List

                //Log.e("aa",json.toString());
                this.data = list;

                chat_list.post(() -> chat_list.scrollToPosition(getItemCount() - 1));

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view;
        RecyclerView.ViewHolder viewHolder;
        if (viewType==RECEIVE) {
            view = LayoutInflater.from(context).inflate(R.layout.item_receive, parent, false);
            viewHolder= new ReceiveViewHolder(view);
        }else {
            view = LayoutInflater.from(context).inflate(R.layout.item_send, parent, false);
            viewHolder=new SendViewHolder(view);
        }
        return viewHolder;
    }

    @Override
    public int getItemViewType(int position) {
        return data.get(position).getMsgType();
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof ReceiveViewHolder) {
            ((ReceiveViewHolder)holder).message.setText(data.get(position).getMessage());
        }else {
            ((SendViewHolder)holder).message.setText(data.get(position).getMessage());
        }

    }


    @Override
    public int getItemCount() {
        return data.size();
    }

    class ReceiveViewHolder extends RecyclerView.ViewHolder{

        private TextView name;
        private TextView message;

        public ReceiveViewHolder(@NonNull View itemView) {
            super(itemView);
            name=itemView.findViewById(R.id.name_receive);
            message=itemView.findViewById(R.id.item_content_receive);
        }
    }

    class SendViewHolder extends RecyclerView.ViewHolder{
        private TextView name;
        private TextView message;

        public SendViewHolder(@NonNull View itemView) {
            super(itemView);
            name=itemView.findViewById(R.id.name_send);
            message=itemView.findViewById(R.id.item_content_send);
        }
    }
}
